﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Controllers;
using Interfaces;

namespace Views.Moduler
{
    public partial class SøgSoftware
    {
        #region Properties

        private readonly Controller _controller;
        private ISoftware _selectedSoftware; 

        #endregion

        #region Creation

        public SøgSoftware(Controller controller)
        {
            InitializeComponent();
            _controller = controller;
            OpdaterSide();
        } 

        #endregion

        #region Eventhandlers

        private void BtnVisSoftware_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedSoftware == null) return;

            var window = new SoftwareUdlån(_selectedSoftware, _controller);
            window.Title = _selectedSoftware.Navn;
            window.ShowDialog();
        }

        private void TxtSøgning_TextChanged(object sender, TextChangedEventArgs e)
        {
            LwSoftware.ItemsSource =
                _controller.HentAltSoftware().Where(s => s.Navn.ToLower()
                                             .Contains(TxtSøgning.Text.ToLower()))
                                             .ToList();
        }

        private void SøgSoftware_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
                TxtSøgning.Clear();
            if (e.Key == Key.Enter)
                TxtSøgning.SelectAll();
        }

        private void LwSoftware_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var software = (ISoftware)LwSoftware.SelectedItem;
            _selectedSoftware = software;

            if (_selectedSoftware == null) return;

            ValgtSoftware();
        }

        #endregion

        #region Methods

        private void ValgtSoftware()
        {
            BtnVisSoftware.IsEnabled = true;
        } 

        #endregion

        #region Tilstandsstyring

        public void OpdaterSide()
        {
            LwSoftware.ItemsSource = null;
            BtnVisSoftware.IsEnabled = false;
            TxtSøgning.Clear();
            TxtSøgning.Focus();

            OpdaterListView();
        }

        private void OpdaterListView()
        {
            LwSoftware.ItemsSource = _controller.HentAltSoftware();
        }

        #endregion
    }
}
